package com.bsj.travel.process.web;

import cn.hutool.extra.spring.SpringUtil;
import com.bsj.consumerQ.Until.ExceptionUntil;
import com.bsj.travel.process.file.log.LogWriteAndRead;
import com.bsj.travel.process.handle.RunAllService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.LinkedList;
import java.util.List;

/**
 * @author yinhao
 * @version 1.0
 * @description 初始化方法
 * @date 2024/1/16
 */
@Component
@Slf4j
public class Action implements CommandLineRunner {

    List<RunAllService> list = new LinkedList<>();

    @Value("${runService}")
    private String runServiceBean;

    @Autowired
    private LogWriteAndRead logWriteAndRead;

    @Override
    public void run(String... args) throws Exception {
        //文件存储
//        LogSaveQueue.start("cloudLog");
//        logWriteAndRead.start("cloudLog");
        //主业务
        if (StringUtils.isNotEmpty(runServiceBean)) {
            String[] beanSplit = runServiceBean.split(";");
            for (String bean : beanSplit) {
                Object beanService = SpringUtil.getBean(bean);
                if (beanService instanceof RunAllService) {
                    RunAllService runService = (RunAllService) beanService;
                    runService.init();
                    list.add(runService);
                } else {
                    log.warn("无法识别的业务名称:" + bean);
                }
            }
        }
    }

    /**
     * 销毁使用的方法
     */
    @PreDestroy
    public void destroy() throws Exception {
        try {
            list.stream().forEach(runService -> {
                runService.stop();
            });
        } catch (Exception e) {
            log.error("关闭错误:" + ExceptionUntil.getErrorStr(e));
        }
        log.info("结束关闭");
    }
}
